# -*- coding: utf-8 -*-
# @time:2021/7/12 16:31
# @Author:龚志伟
# @File: main
import os
import sys
import OCC.Display.backend

used_backend = OCC.Display.backend.load_backend("qt-pyside2")
from OCC.Core.BRepAdaptor import BRepAdaptor_Surface
from OCC.Core.STEPControl import STEPControl_Reader
from OCC.Core.TopAbs import TopAbs_FACE
from OCC.Core.TopExp import TopExp_Explorer
from OCC.Core.TopoDS import topods
from OCC.Display.qtDisplay import qtViewer3d
from PySide2 import QtWidgets
from PySide2.QtWidgets import QApplication, QMessageBox
from PySide2.QtUiTools import QUiLoader
from lib.share import SI

SI.work_dir = os.path.dirname(sys.argv[0])


class MdiChild(qtViewer3d):

    def __init__(self):
        super().__init__()


class MainWindow:

    def __init__(self):
        # 从文件中加载UI定义

        # 从 UI 定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如 self.ui.button , self.ui.textEdit
        self.ui = QUiLoader().load(os.path.join(SI.workDir, 'ui', 'main.ui'))
        self.occViewer = MdiChild()
        self.ui.mdiArea.addSubWindow(self.occViewer)
        self.occDisplay = self.occViewer._display
        self.ui.actionImport.triggered.connect(onImport)
        # self.ui.button.clicked.connect(self.handleCalc)


def onImport(self):
    self.stp_file, fileType = QtWidgets.QFileDialog.getOpenFileName(self, "选取stp模型文件", self.workdir,
                                                                    "stp Files(*.stp *.step);;All Files(*)")

    if not os.path.exists(self.stp_file):
        return
    self.stp_view._display.EraseAll()  # 重置清空模型
    self.selected_faces = []  # 存储选择的面ID
    self.shp_id_dict = {}  # 表，存储面ID和hashcode的对应关系
    shp_face_id = 1  # 初始化面ID
    self.upper_hashcode = 100000000  # hashcode的上限值

    # 通过STEPControl_Reader()打开模型
    if self.stp_file:
        # Read the file and get the shape
        self.reader = STEPControl_Reader()
        # try:
        #     self.reader
        # except AttributeError:
        #     self.reader = STEPControl_Reader()
        # else:
        #     self.reader = STEPControl_Reader()
        # tr = step_reader.WS().TransferReader().TransientProcess()
        self.reader.ReadFile(self.stp_file)
        self.reader.TransferRoots()
        shape = self.reader.OneShape()
        # Explore the faces of the shape (these are known to be named)
        exp = TopExp_Explorer(shape, TopAbs_FACE)
        while exp.More():
            # rgb = None
            s = exp.Current()
            exp.Next()
            # Converting TopoDS_Shape to TopoDS_Face
            face = topods.Face(s)

            # Working on the geometry
            face_adaptor = BRepAdaptor_Surface(face)
            face_type = face_adaptor.GetType()
            # 记录面的ID {hashcode:ID,……}
            self.shp_id_dict[face.HashCode(self.upper_hashcode)] = shp_face_id
            shp_face_id += 1

            # 区分面的类型，获取面的相关属性
            # if face_type == GeomAbs_Cylinder:
            #     cylinder = face_adaptor.Cylinder()
            #     entity = {}
            #     entity['type'] = 'cylinder'
            #     entity['location'] = cylinder.Axis().Location().Coord()
            #     entity['direction'] = cylinder.Axis().Direction().Coord()
            #     entity['radius'] = cylinder.Radius()
            #     entity['coefficients'] = cylinder.Coefficients()
            #     print('cylinder:', entity)

        # print(sorted(self.shp_id_dict.items(), key=lambda x: x[1]))
        # Display
        self.stp_view._display.DisplayShape(shape, update=True, transparency=0.2)
        # 自动调整视图
        self.stp_view._display.FitAll()
        # 设置选择方式为面
        self.stp_view._display.SetSelectionModeFace()

        self.addMessage("成功导入几何模型")
        # self.stp_view.sig_topods_selected.connect(self.on_select)
        if not self.occ_clicked_envent:
            self.stp_view._display.register_select_callback(self.on_select)
            self.occ_clicked_envent = True
    else:
        self.addMessage("未选择正确的文件，请重新操作")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    SI.main_win = QUiLoader().load(os.path.join(SI.work_dir, 'ui', 'main.ui'))
    occ_viewer = MdiChild()
    SI.main_win.mdiArea.addSubWindow(occ_viewer)
    occ_display = occ_viewer._display
    occ_viewer.InitDriver()
    SI.main_win.show()
    sys.exit(app.exec_())
